package com.swust.servlet;

import com.swust.dao.User;
import com.swust.service.LibServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegistServlet",urlPatterns = {"/RegistServlet"})
public class RegistServlet extends HttpServlet {

    private LibServiceImpl libService = new LibServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        User user = new User(userName, password, phone, email);
        if (libService.regist(user)) {
            // 如果注册成功跳转到登陆页面
            request.getSession().setAttribute("username", user.getUserName());
            response.sendRedirect(request.getContextPath() + "/view/index.jsp");
        } else {
            //如果注册失败提醒用户 用户名重复
            request.setAttribute("msg", "您的用户名已被注册");
            request.getRequestDispatcher("/view/regist.jsp").forward(request,response);
        }
        System.out.println(userName);
        System.out.println(password);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
